/*
 * Copyright (C) 2011-2021 ShenZhen iBOXCHAIN Information Technology Co.,Ltd.
 *
 * All right reserved.
 *
 * This software is the confidential and proprietary
 * information of iBOXCHAIN Company of China.
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with iBOXCHAIN inc.
 *
 */
package cn.anoxia.springframework.beans.support;

import cn.anoxia.springframework.beans.BeansException;
import cn.anoxia.springframework.beans.factory.BeanDefinition;
import cn.anoxia.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @author huangle
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

  private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

  @Override
  public BeanDefinition getBeanDefinition(String name) throws BeansException {
    BeanDefinition definition = beanDefinitionMap.get(name);
    if (definition == null){
      throw new BeansException("没有名称为"+name+"的bean");
    }
    return definition;
  }

  @Override
  public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
    beanDefinitionMap.put(beanName,beanDefinition);
  }

  @Override
  public boolean containsBeanDefinition(String beanName) {
    Assert.notNull(beanName, "Bean name must not be null");
    return this.beanDefinitionMap.containsKey(beanName);
  }

  @Override
  public <T> Map<String, T> getBeansOfType(Class<T> var1) throws BeansException {
    Map<String,T> map = new HashMap<>();
    beanDefinitionMap.forEach((name,beanDefinition)->{
      Class beanClass = beanDefinition.getBeanClass();
      if (var1.isAssignableFrom(beanClass)){
        try {
          map.put(name, (T) getBean(name));
        } catch (BeansException e) {
          e.printStackTrace();
        }
      }
    });
    return map;
  }

  @Override
  public String[] getBeanDefinitionNames() {
    return beanDefinitionMap.keySet().toArray(new String[0]);
  }

  @Override
  public void preInstantiateSingletons() throws BeansException {
    for (String s : beanDefinitionMap.keySet()) {
      getBean(s);
    }
  }
}
